package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"regi-sys/cache"
	"regi-sys/model"
	"time"

	"regi-sys/regirpc/internal/svc"
	"regi-sys/regirpc/regirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegiDetailLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegiDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegiDetailLogic {
	return &RegiDetailLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 挂号详情
func (l *RegiDetailLogic) RegiDetail(in *regirpc.RegiDetailRequest) (*regirpc.RegiDetailResponse, error) {
	// todo: add your logic here and delete this line

	var regi model.Regi
	key := fmt.Sprintf("regi_detail_%d", in.RegiId)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData == "" {
		err := regi.RegiDetailById(model.DB, in.RegiId)
		if err != nil {
			return nil, err
		}
		jsonData, _ := json.Marshal(regi)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*30)
	} else {
		json.Unmarshal([]byte(cacheData), &regi)
	}

	return &regirpc.RegiDetailResponse{
		RegiId:   int64(regi.ID),
		RegiName: regi.RegiName,
		RegiCode: regi.RegiCode,
		Tel:      regi.Tel,
		Address:  regi.Address,
	}, nil
}
